package com.asseco.mio.codex.controllers;

import com.asseco.mio.UserInstitution;
import com.asseco.mio.codex.Institution;
import com.asseco.mio.codex.UserInstitutionsForm;
import com.asseco.mio.core.webapp.controller.BaseFormController;
import com.asseco.persistence.service.HibernateUtil;
import org.appfuse.model.User;
import org.appfuse.service.UserManager;
import java.util.ArrayList;
import java.util.List;
import java.util.Locale;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.appfuse.service.GenericManager;
import org.hibernate.Criteria;
import org.hibernate.Session;
import org.hibernate.criterion.Restrictions;
import org.springframework.beans.factory.annotation.Qualifier;

/**
 * Implementation of <strong>SimpleFormController</strong> that interacts with
 * the {@link UserManager} to retrieve/persist values to the database.
 *
 * <p><a href="UserFormController.java.html"><i>View Source</i></a>
 *
 * @author <a href="mailto:matt@raibledesigns.com">Matt Raible</a>
 */
@Controller
@RequestMapping("/chooseinstitution*")
public class ChooseInstitutionController extends BaseFormController {

    private UserManager userManager = null;
    private GenericManager<Institution, String> institutionManager = null;
    private GenericManager<UserInstitution, String> userInstitutionManager = null;


    @Autowired
    public void setUserManager(UserManager userManager) {
        this.userManager = userManager;
    }

    @Autowired
    public void setInstitutionManager(@Qualifier("institutionManager") GenericManager<Institution, String> institutionManager) {
        this.institutionManager = institutionManager;
    }

    @Autowired
    public void setUserInstitutionManager(@Qualifier("userInstitutionManager") GenericManager<UserInstitution, String> userInstitutionManager) {
        this.userInstitutionManager = userInstitutionManager;
    }

    public ChooseInstitutionController() {
        setCancelView("redirect:mainMenu");
        setSuccessView("redirect:userinstitutionsearch");
    }

    @ModelAttribute
    public UserInstitutionsForm userInstitutionsForm() {
        UserInstitutionsForm x = new UserInstitutionsForm(new User(), null,getAllActiveInstitutions(institutionManager.getAll()));
        return x;
    }

    @ModelAttribute
    @RequestMapping(method = RequestMethod.POST)
    public String onSubmit(UserInstitutionsForm userInstitutionsForm, BindingResult errors, HttpServletRequest request,
                           HttpServletResponse response)
            throws Exception {


        String success = getSuccessView();
        Locale locale = request.getLocale();
        Institution inst = institutionManager.get(userInstitutionsForm.getInstitution().getId());
        userInstitutionsForm.setInstitution(inst);
        UserInstitution uInstitution = new UserInstitution();
        uInstitution.setUser(userInstitutionsForm.getUser());
        uInstitution.setInstitution(userInstitutionsForm.getInstitution());

        User u = userManager.get(userInstitutionsForm.getUser().getId());

        Session session = HibernateUtil.getSessionFactory().openSession();
        session.beginTransaction();

        Criteria criteria  = session.createCriteria(UserInstitution.class).add(Restrictions.like("user", u));
        List result = criteria.list();
        session.getTransaction().commit();
        uInstitution.setUser(u);
       
        if (result.isEmpty()){
            userInstitutionManager.save(uInstitution);
            saveMessage(request, getText("userInstitution.InstitucijataEDodadena", locale));    
        }
        else {
            UserInstitution i = (UserInstitution) result.get(0);
            userInstitutionManager.remove(i.getId());
            userInstitutionManager.save(uInstitution);
            saveMessage(request, getText("userInstitution.InstitucijataEDodadenaZaIzbraniotUser", locale));
        }

        return success;
    }

    @ModelAttribute
    @RequestMapping(method = {RequestMethod.GET, RequestMethod.POST})
    public UserInstitutionsForm showForm(HttpServletRequest request, HttpServletResponse response)
            throws Exception {

             long id = (long) Integer.parseInt(request.getParameter("id"));

        UserInstitutionsForm userInstitutionsForm = this.userInstitutionsForm();
        User tempUser = userManager.get(id);

        userInstitutionsForm.getUser().setFirstName(tempUser.getFirstName());
        userInstitutionsForm.getUser().setLastName(tempUser.getLastName());
        userInstitutionsForm.getUser().setUsername(tempUser.getUsername());
        userInstitutionsForm.getUser().setId(id);

        Session session = HibernateUtil.getSessionFactory().openSession();
        session.beginTransaction();
        Criteria criteria  = session.createCriteria(UserInstitution.class).add(Restrictions.like("user", tempUser));
        List result = criteria.list();
        session.getTransaction().commit();
       // userInstitutionsForm.setSelectedInstitutions(result);

        UserInstitutionsForm x = new UserInstitutionsForm(tempUser, result, getAllActiveInstitutions(institutionManager.getAll()));


        return x;
    }

    public List getAllActiveInstitutions(List<Institution> list) {

        List result = new ArrayList();
        for (int i = 0; i < list.size(); i++) {
            Institution ga = list.get(i);
            if (ga.getStatus() == true) {
                result.add(ga);
            }

        }

        return result;
    }
}

